package com.nwpu.intimacy.friend;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.chat.ChatActivity;
import com.nwpu.intimacy.main.MainActivity;
import com.nwpu.intimacy.utils.CacheUtil;

public class FriendInformationActivity extends Activity {

	private static final String URL_ADD = "http://10.128.51.203:8080/SoftwareEngineer/addUser";
	private static final String URL_DELETE = "http://10.128.51.203:8080/SoftwareEngineer/delete";

	private final static int USER_ADD_SUCCESS = 0x114;
	private final static int USER_ADD_FAIL = 0x115;
	private final static int USER_DELETE_SUCCESS = 0x116;
	private final static int USER_DELETE_FAIL = 0x117;

	private TextView sex_friend;
	private TextView hometown_friend;
	private TextView comment_friend;

	private Button sendMessage;
	private Button addORdeleteFriend;

	private ImageView user_image_my;
	private TextView user_name_friend;
	private ImageView qrCode_user;

	private SharedPreferences sp_userMessage;

	private Handler addHandler;

	private static String str1;
	private static String str2;
	private static String str3;
	private static String str4;
	private static String str5;
	private static Bitmap bitmap;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friendinformation);

		getActionBar().hide();

		initLayout();
		initMessage();

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		sendMessage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ChatActivity.class);
				intent.putExtra("friendname", str1);
				startActivity(intent);

				try {

					CacheUtil.writeToFile(str1, "UserChat", "Send/User");

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				finish();

			}
		});

		addORdeleteFriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (addORdeleteFriend.getText().toString().equals("Add Friend")) {

					addFriend();

				} else {

					deleteFriend();
				}

			}
		});

		addHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_ADD_SUCCESS: {
					// 请求添加好友请求发送成功

					Toast.makeText(getApplicationContext(), "添加请求已处理，请等待回复!",
							Toast.LENGTH_SHORT).show();
					finish();

					break;
				}
				case USER_DELETE_SUCCESS: {
					// 删除好友请求发送成功

					try {

						String str = CacheUtil.getFromFile(
								"friendsInformation", "Friend");

						JSONArray jsonArray = new JSONArray(str);
						JSONArray jsonArray_new = new JSONArray();

						for (int i = 0; i < jsonArray.length(); i++) {

							JSONObject jsonObject = (JSONObject) jsonArray
									.get(i);

							if (!msg.obj.toString().equals(
									jsonObject.optString("username"))) {

								jsonArray_new.put(jsonObject);

							}

						}

						CacheUtil.writeToFile(jsonArray_new.toString(),
								"friendsInformation", "Friend");

						setResult(Activity.RESULT_OK);
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								MainActivity.class);
						intent.putExtra("setPosition", 1);
						startActivity(intent);

						finish();

						break;

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				default:
					super.handleMessage(msg);
					break;
				}
			}

		};

	}

	/**
	 * 初始化控件
	 */
	private void initLayout() {

		sex_friend = (TextView) findViewById(R.id.sex_friendinformation);
		hometown_friend = (TextView) findViewById(R.id.hometown_friendinformation);
		comment_friend = (TextView) findViewById(R.id.comment_friendinformation);

		sendMessage = (Button) findViewById(R.id.send_message);
		addORdeleteFriend = (Button) findViewById(R.id.add_or_delete_friend);

		user_name_friend = (TextView) findViewById(R.id.user_name_my);
		qrCode_user = (ImageView) findViewById(R.id.qrCode_user);
		user_image_my = (ImageView) findViewById(R.id.user_image_my);

	}

	/**
	 * 静态方法，其他Activity跳转时调用
	 * 
	 * @param str1
	 * @param str2
	 * @param str3
	 * @param str4
	 * @param str5
	 * @param bitmap
	 */
	public static void initInformation(String str1, String str2, String str3,
			String str4, String str5, Bitmap bitmap) {

		FriendInformationActivity.str1 = str1;
		FriendInformationActivity.str2 = str2;
		FriendInformationActivity.str3 = str3;
		FriendInformationActivity.str4 = str4;
		FriendInformationActivity.str5 = str5;
		FriendInformationActivity.bitmap = bitmap;

	}

	/**
	 * 初始化界面内容
	 * 
	 * @param str1
	 * @param str2
	 * @param str3
	 * @param str4
	 * @param str5
	 */
	/**
	 * 
	 */
	public void initMessage() {

		qrCode_user.setVisibility(View.GONE);
		user_name_friend.setText(str1);

		if (str2.equals("0")) {

			sex_friend.setText("Secret");

		} else if (str2.equals("1")) {

			sex_friend.setText("Male");

		} else if (str2.equals("1")) {

			sex_friend.setText("Female");

		}

		String[] strarray = str3.split(";", 2);
		hometown_friend.setText(strarray[1]);

		comment_friend.setText(str4);
		addORdeleteFriend.setText(str5);

		Drawable drawable = new BitmapDrawable(bitmap);

		user_image_my.setImageDrawable(drawable);

		if (str5.equals("Add Friend")) {

			sendMessage.setEnabled(false);

		} else {

			sendMessage.setEnabled(true);

		}

	}

	private void addFriend() {

		new Thread() {

			public void run() {

				try {

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("friendname", user_name_friend.getText()
							.toString());
					jsonObject.put("hostname",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("status", 1);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL_ADD);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"addUser", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					Log.e("keyword", result);
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("status").equals("success")) {

						Message msg = new Message();
						msg.what = USER_ADD_SUCCESS;
						msg.obj = result;
						addHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_ADD_FAIL;
						msg.obj = result;
						addHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	private void deleteFriend() {

		new Thread() {

			public void run() {

				try {

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("friendname", user_name_friend.getText()
							.toString());
					jsonObject.put("hostname",
							sp_userMessage.getString("USER_NAME", ""));

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL_DELETE);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("delete",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					Log.e("keyword", result);
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("status").equals("success")) {

						Message msg = new Message();
						msg.what = USER_DELETE_SUCCESS;
						msg.obj = user_name_friend.getText().toString();
						addHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_DELETE_FAIL;
						msg.obj = result;
						addHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	/**
	 * 单击退出界面
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:

			Intent intent = new Intent();

			intent.setClass(getApplicationContext(), MainActivity.class);

			startActivity(intent);

			finish();

			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

}
